package com.sky.service.impl;

import com.sky.constant.OrdersConstant;
import com.sky.dto.GoodsSalesDTO;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.sky.constant.OrdersConstant.ORDERS_STATUS_COMPLETED;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 根据日期统计营业额
     * @param begin
     * @param end
     * @return
     */
    //TODO 能否进行简化
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {

        // 获取日期字符串
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Double> amounts = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime min = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime max = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("beginTime", min);
            map.put("endTime", max);
            map.put("status", ORDERS_STATUS_COMPLETED);

            Double amount = orderMapper.getAmount(map);
            amount = amount == null ? 0.0 : amount;

            amounts.add(amount);
        }

        String replace = dateList.toString().replace("[", "").replace("]", "");
        String turnoverList = amounts.toString().replace("[", "").replace("]", "");
        return TurnoverReportVO.builder()
                                .dateList(replace)
                                .turnoverList(turnoverList)
                                .build();
    }

    /**
     * 用户统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        // 生成日期列表
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate localDate : dateList) {
            LocalDateTime min = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime max = LocalDateTime.of(localDate, LocalTime.MAX);

            Map map = new HashMap();
            map.put("endTime", max);
            // 获取总用户人数
            Integer totalUserCount = userMapper.getCount(map);
            totalUserList.add(totalUserCount);
            // 获取新增用户人数
            map.put("beginTime", min);
            Integer newUserCount = userMapper.getCount(map);
            newUserCount = newUserCount == null ? 0 : newUserCount;
            newUserList.add(newUserCount);
        }

        String dateListString = dateList.toString().replace("[", "").replace("]", "");
        String newUserListString = newUserList.toString().replace("[", "").replace("]", "");
        String totalUserListString = totalUserList.toString().replace("[", "").replace("]", "");

        return UserReportVO
                .builder()
                .dateList(dateListString)
                .newUserList(newUserListString)
                .totalUserList(totalUserListString)
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime min = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime max = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("beginTime", min);
            map.put("endTime", max);
            Integer orderCount = orderMapper.getOrdersCount(map);
            orderCount = orderCount == null ? 0 : orderCount;
            orderCountList.add(orderCount);

            map.put("status", ORDERS_STATUS_COMPLETED);
            Integer validOrderCount = orderMapper.getOrdersCount(map);
            validOrderCount = validOrderCount == null ? 0 : validOrderCount;
            validOrderCountList.add(validOrderCount);
        }

        Integer orderCountSum = orderCountList.stream().mapToInt(Integer::intValue).sum();
        Integer validOrderCountSum = validOrderCountList.stream().mapToInt(Integer::intValue).sum();

        Double orderCompletionRate = Double.valueOf(validOrderCountSum ) / Double.valueOf(orderCountSum);

        String dateListString = dateList.toString().replace("[", "").replace("]", "");
        String orderCountListString = orderCountList.toString().replace("[", "").replace("]", "");
        String validOrderCountListString = validOrderCountList.toString().replace("[", "").replace("]", "");

        return OrderReportVO
                    .builder()
                    .dateList(dateListString)
                    .orderCountList(orderCountListString)
                    .totalOrderCount(orderCountSum)
                    .validOrderCountList(validOrderCountListString)
                    .validOrderCount(validOrderCountSum)
                    .orderCompletionRate(orderCompletionRate)
                    .build();
    }

    /**
     * top10销量统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO topStatistics(LocalDate begin, LocalDate end) {
        LocalDateTime min = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime max = LocalDateTime.of(end, LocalTime.MAX);

        Map map = new HashMap();
        map.put("beginTime", min);
        map.put("endTime", max);
        List<GoodsSalesDTO> goodsSalesDTOS = orderMapper.topStatistics(map);

        List<String> nameList = goodsSalesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = goodsSalesDTOS.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        String nameListString = nameList.toString().replace("[", "").replace("]", "");
        String numberListString = numberList.toString().replace("[", "").replace("]", "");


        return SalesTop10ReportVO
                        .builder()
                        .nameList(nameListString)
                        .numberList(numberListString)
                        .build();
    }

    /**
     * 导出EXcel报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {

        // 1. 查询数据库，获取营业数据 30天内的概览数据
        LocalDate beginTime = LocalDate.now().minusDays(30);
        LocalDate endTime = LocalDate.now().minusDays(1);
        BusinessDataVO businessDataVO = workspaceService.businessData(beginTime, endTime);

        // 2. 通过POI将数据写入到Excel文件中

        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            // 根据模板文件创建一个新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            // 获取工作表
            XSSFSheet sheet = excel.getSheet("Sheet1");
            // 2.1 写入概览数据
            //单元格赋值
            sheet.getRow(1).getCell(1).setCellValue("日期：" + beginTime + "至" + endTime);

            XSSFRow row1 = sheet.getRow(3);
            row1.getCell(2).setCellValue(businessDataVO.getTurnover());
            row1.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row1.getCell(6).setCellValue(businessDataVO.getNewUsers());

            XSSFRow row2 = sheet.getRow(4);
            row2.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row2.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            // 2.2 写入详细数据
            for (int i = 0; i < 30; i++) {
                BusinessDataVO businessData = workspaceService.businessData(beginTime, beginTime);
                XSSFRow row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(beginTime.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
                beginTime = beginTime.plusDays(1);
            }
            // 3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            in.close();
            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
